package edu.sjtu.context.prob.local;

import java.util.ArrayList;
import java.util.List;
import java.net.InetAddress;

import sun.management.ManagementFactory;

import edu.sjtu.context.core.ContextChangeEvent;
import edu.sjtu.context.core.LocalContextChangeListener;
import edu.sjtu.context.core.PublishContext;
import edu.sjtu.context.prob.LocalContextProb;
import edu.sjtu.context.core.ContextTopic;

public class LocalIPProb implements LocalContextProb,PublishContext {
	/**
	 * list of listeners
	 */
	private List<LocalContextChangeListener> lis;
	/**
	 * Detect frequency in milliseconds. Default value is one minute. 
	 */
	private long frequency;

	/**
	 * current ipAddress
	 */
	private String ipAddress="";
	
	/**
	 * constructor.
	 * @param frequency
	 */
	public LocalIPProb(){
		this.lis = new ArrayList<LocalContextChangeListener>();
		this.frequency = 60000;
	}
	
	/**
	 * Add local context change listener to the probe.
	 * @param lis
	 * 		listener to be added.
	 */
	public void addLocalContextChangeListener(LocalContextChangeListener lis) {
		this.lis.add(lis);
	}

	/**
	 * get detection frequency.
	 * @return
	 * 		detection frequency.
	 */
	public long getFrequency() {
		return frequency;
	}

	/**
	 * remove local context change listener from the probe.
	 * @param lis
	 * 		listener to be removed.
	 * @return
	 * 		the index of the listener which will be removed in the probe's listener list. 
	 */
	public int removeLocalContextChangeListener(LocalContextChangeListener lis) {
		int index = this.lis.indexOf(lis);
		this.lis.remove(lis);
		return index;
	}

	/**
	 * set detection frequency.
	 * @param frequency
	 * 		detection frequency.
	 */
	public void setFrequency(long frequency) {
		this.frequency = frequency;
	}

	/**
	 * Implement ip detection logic in this method. The probe will be run in a new Thread.
	 * The detection frequency is determined by frequency which is property in this class.
	 */
	public void run() {
		String ip;
		ContextChangeEvent event;
		while(true){
			try {
				ip = InetAddress.getLocalHost().getHostAddress();	
				
				if(!this.ipAddress.equals(ip)){
					this.ipAddress = ip;
					event = new ContextChangeEvent(this, "ip", this.ipAddress, "", "Environment");
					for(LocalContextChangeListener li : this.lis){
						li.sendLocalContext(event);
					}
				}
				Thread.sleep(this.frequency);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (Exception e){
				e.printStackTrace();
			}
		}
	}

	public String getTopic(){
		return ContextTopic.IP;
	}
}
